package org.geektimes.projects.user.web.controller;

import org.geektimes.projects.user.domain.User;
import org.geektimes.projects.user.service.UserService;
import org.geektimes.web.mvc.controller.PageController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.io.*;
import java.util.Collection;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 * 输出 “Hello,World” Controller
 */
@Path("/user")
public class RegisterController implements PageController {
    private final Logger logger = Logger.getLogger(getClass().getName());


    @Resource(name = "bean/UserService")
    private UserService userService;


    @GET
    @POST
    @Path("/registerPage") // /hello/world -> HelloWorldController
    public String registerPage(HttpServletRequest request, HttpServletResponse response) throws Throwable {
        return "register-form.jsp";
    }


    @POST
    @Path("/postRegister") // /hello/world -> HelloWorldController
    public String postRegister(HttpServletRequest request, HttpServletResponse response) throws Throwable {
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String phoneNumber = request.getParameter("phoneNumber");

        User user = new User();
        user.setName(userName);
        user.setPassword(password);
        user.setEmail(email);
        user.setPhoneNumber(phoneNumber);

        try {
            ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
            Validator validator = factory.getValidator();
            Set<ConstraintViolation<User>> violations = validator.validate(user);

            if(!violations.isEmpty()) {
                violations.forEach(c -> {
                            System.out.println(c.getMessage());
                        }
                );
                return "register-error.jsp";
            }

            if (userService.register(user)) {
                return "register-success.jsp";
            } else {
                return "register-error.jsp";
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, "注册用户出错", e);
            return "register-error.jsp";
        }
    }

    @GET
    @Path("/infos") // /hello/world -> HelloWorldController
    public String infos(HttpServletRequest request, HttpServletResponse response) throws Throwable {
        Collection<User> allUser = userService.findAll();
        for (User user : allUser) {
            System.out.println(user);
        }
        return "register-form.jsp";
    }
}